//出栈pop，压栈push

function smartRepeat(templateStr) {
    //指针
    var index = 0;
    //栈，栈1为数字，栈2为结果字符串
    var stack1 = [],
        stack2 = [];
    //剩余部分
    var rest = templateStr;

    while (index < templateStr.length - 1) {
        rest = templateStr.substring(index);

        if (/^\d+\[/.test(rest)) {
            //得到数字
            let times = rest.match(/^(\d+)\[/)[1];
            //指针后移位数，包含[
            index += times.length + 1;
            //数字压栈1，空字符串压栈2
            stack1.push(+times);
            stack2.push('');
        } else if (/^\w+\]/.test(rest)) {
            //如果是字母
            let word = rest.match(/^(\w+)\]/)[1];
            stack2[stack2.length - 1] = word;
            index += word.length;

        } else if (rest[0] == ']') {
            //如果是]
            //栈1弹栈，栈2弹栈，栈2弹出项字符重复，拼接剩余字符串
            let times = stack1.pop();
            let word = stack2.pop();
            stack2[stack2.length - 1] = word.repeat(times);
            index++;
        }
        // console.log(index, stack1, stack2);

    }
    return stack2[0].repeat(stack1[0]);
}

var res = smartRepeat('3[2[abc]4[d]]')
console.log(res);